import React, { useState, useEffect } from 'react';
import {connect} from 'dva';
import { Form, Input, Button, Drawer } from 'antd';
import Cron from 'cron-editor-react';
import SeeCronNextDate from "@/pages/common/cron/SeeCronNextDate";

const InputGroup = Input.Group;

/**
 * 选择 Cron
 *
 * @author zhangby
 * @date 28/2/20 2:27 pm
 */
function SelectCron(props,ref) {
  const [visible, setVisible] = useState(false);
  const [cron, setCron] = useState("* * * * * ?");
  const [inputVal, setInputVal] = useState("* * * * * ?");

  const { render, value } = props;

  // 初始化
  useEffect(() => {
    const val =  value !== undefined ? value : '* * * * * ?';
    setCron(val);
    setInputVal(val);
  },[value])

  // 加载
  const initSelectCron = () => {
    setVisible(true);
  }

  // 提交
  const handleSubmit = () => {
    setInputVal(cron);
    if (render !== undefined) {
      render(cron);
    }
    setVisible(false);
  }

  return (
    <div>
      <InputGroup compact>
        <Input style={{ width: 240 }} disabled value={inputVal} />
        <Button type="primary" onClick={initSelectCron}>
          cron
        </Button>
      </InputGroup>
      {/* 弹出层 */}
      <Drawer
        title="选择Cron表达式"
        placement="right"
        onClose={() => setVisible(false)}
        visible={visible}
        bodyStyle={{ paddingBottom: 80 }}
        width={680}
      >
        <Cron showCrontab value={cron} onChange={val => setCron(val)} />
        <SeeCronNextDate key={cron} value={cron} />
        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={() => setVisible(false)} style={{ marginRight: 8 }}>
            Cancel
          </Button>
          {/* eslint-disable-next-line react/jsx-no-bind */}
          <Button onClick={handleSubmit} type="primary">
            Submit
          </Button>
        </div>
      </Drawer>
    </div>
  )
}


const form = Form.create({name: 'SelectCron',})(SelectCron)

export default connect(({cron}) => ({
  cron: cron
}))(form);
